class Api::V1::BaseController < ActionController::API
  before_action :authenticate_request!, :load_current_area

  include ActionView::Rendering

  include ApplicationHelper
  helper_method :formattime, :i18n_enum, :has_image?

  def render_to_body(options)
    _render_to_body_with_renderer(options) || super
  end

  protected

  def authenticate_request!
    if !payload || !JsonWebToken.valid_payload(payload.first)
      return invalid_authentication
    end

    load_current_user!
    invalid_authentication unless @current_user
    if @current_user.pending? || @current_user.disagree?
      invalid_authentication
    end
  end

  def authenticate_request
    if payload && JsonWebToken.valid_payload(payload.first)
      load_current_user!
      if @current_user.presence
        if @current_user.pending? || @current_user.disagree?
          invalid_authentication
        end
      end
    end
  end

  # Return 401 response. To handle malformed / invalid requests.
  def invalid_authentication
    render json: { error: 'Invalid Request' }, status: :unauthorized
  end

  def shops_where_area(query, area_id)
    if Setting.fetch("city_or_district") == 'city'
      query.where(city_id: area_id)
    elsif Setting.fetch("city_or_district") == 'district'
      query.where(district_id: area_id)
    else
      query
    end
  end

  def spus_where_area(query, area_id)
    if Setting.fetch("city_or_district") == 'city'
      query.joins(:shop).where("shops.city_id = ?", area_id)
    elsif Setting.fetch("city_or_district") == 'district'
      query.joins(:shop).where("shops.district_id = ?", area_id)
    else
      query
    end
  end

  private

  def payload
    auth_header = request.headers['Authorization']
    token = auth_header.split(' ').last
    JsonWebToken.decode(token)
  rescue
    nil
  end

  def load_current_user!
    @current_user = User.find_by(id: payload[0]['user_id'])
  end

  def load_current_area
    if Setting.fetch("city_or_district") == 'city'
      @current_area = City.find_by_adcode(request.headers['adcode'])
    else
      @current_area = District.find_by_adcode(request.headers['adcode'])
    end
  end

  def render_errors(messages)
    msgs = []
    messages.each do |key, vals|
      vals.each do |val|
        msgs.push({
          "source": {
            "pointer": "data/attributes/#{key}"
          },
          "detail": val
        })
      end
    end
    msgs
  end

end